package thread.blocking.demo;

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

public class Main {

    public static String gen16Random(){
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 16; i++) {
            int index = random.nextInt(characters.length());
            sb.append(characters.charAt(index));
        }
        return new String(sb);
    }
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        LinkedBlockingQueue<User> toBackendQueue = new LinkedBlockingQueue<>();
        BlockingHashMap<Long, User> toFrontQueue = new BlockingHashMap<>();

        for (int i = 0; i < 10; i++) {
            executorService.submit(new ProcessJob(toBackendQueue, toFrontQueue));
        }

        //准备数据
        ArrayList<User> users = new ArrayList<>();
        for (int i = 0; i < 100L; i++) {
            User user = new User();
            user.setUserId(Long.valueOf(i));
            user.setUserName("user" + i);
            user.setSalary("" + i);
            user.setPhoneNumber("17777777" + i);
            user.setKey(gen16Random());
            user.setData(("test"+i).getBytes());
            users.add(user);
        }

        //开始处理
        for (int i = 0; i < users.size(); i++) {
            User user = users.get(i);
            //放入数据
            toBackendQueue.put(user);
            //等待返回
            toFrontQueue.take(users.get(i).getUserId());
        }

        //输出数据内容
        for (int i = 0; i < users.size(); i++) {
            System.out.println(users.get(i));
        }

    }
}
